package com.king.security.service;

import com.king.security.entity.MyUser;
import com.king.security.repository.UserRepository;
import com.king.security.security.MyPasswordEncoder;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author KING
 * @date 2018/8/30 20:33
 */

@Setter
@Getter
public class UserService {


    public MyPasswordEncoder myPasswordEncoder;
    private EntityManager em;


    private UserRepository userRepository;

    /**
     * 获取所有用户
     *
     * @return
     */
    public List<MyUser> findAll() {
        return userRepository.findAll();
    }

    @Transactional
    public MyUser add(MyUser user) {
        if (!StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(myPasswordEncoder.encode(user.getPassword()));
        }
        return userRepository.save(user);
    }

    @Transactional
    public List<MyUser> addUser() {
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
        String formattedDate = dateFormat.format(date);
        List<MyUser> users = new ArrayList<>();

        List<MyUser> myUserList = userRepository.findAll();
        int tolo = myUserList.size();
        for (int i = tolo + 1; i < tolo + 51; i++) {
            //保存或更新
            MyUser user = new MyUser();
            user.setId(i + 0L);
            user.setUserName("张三" + i);
            user.setEmail("q@qq.com" + i);
            user.setNickName("NickName" + i);
            user.setPassword("PassWord" + i);
            user.setRegTime(formattedDate);
            System.out.println("user:" + user);
            users.add(user);
        }
        int iin = users.size();
        System.out.println("users.size:" + iin);
        for (int j = 0; j < iin; j++) {
            System.out.println("开始" + j);
            em.merge(users.get(j));
            if (j % 30 == 0) {
                em.flush();
                em.clear();
            }
        }
        em.flush();
        em.clear();
        return users;
    }
}
